﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Windows.Input;
using System.Windows.Controls;
using System.Runtime.InteropServices;

namespace MetaTracker.ViewModel
{
    internal class AddUserViewModel : TrackerBaseViewModel
    {
        #region Data and Properties

        public string NewUserName { get; set; }
        public SecureString NewPassword { get; set; }
        public SecureString NewPasswordConfirmation { get; set; }
        private string _errorMessage = "";
        public string ErrorMessage 
        {
            get
            {
                return _errorMessage;
            }
            set
            {
                _errorMessage = value;
                NotifyPropertyChanged("ErrorMessage");
            }
        }

        #endregion //Data and Properties

        #region Constructors
        internal AddUserViewModel()
        {
            NewUserName = "";

        }
        #endregion //Constructors

        #region Commands
        
        
        #endregion //Commands

        #region Methods

        public bool Register(SecureString one, SecureString two)//(PasswordBox one, PasswordBox two)
        {
            //http://social.msdn.microsoft.com/Forums/en-US/clr/thread/555a5cb6-790d-415d-b079-00d62b3a9632/
            if (one == null || two == null || one.Length != two.Length)
            {
                ErrorMessage = "Passwords do not match";
                return false;
            }

            IntPtr ss_bstr1_ptr = IntPtr.Zero;
            IntPtr ss_bstr2_ptr = IntPtr.Zero;

            try
            {
                ss_bstr1_ptr = Marshal.SecureStringToBSTR(one);
                ss_bstr2_ptr = Marshal.SecureStringToBSTR(two);

                unsafe
                {
                    for (Char* ptr1 = (Char*)ss_bstr1_ptr.ToPointer(), ptr2 = (Char*)ss_bstr2_ptr.ToPointer();
                        *ptr1 != 0 && *ptr2 != 0;
                         ++ptr1, ++ptr2)
                    {
                        if (*ptr1 != *ptr2)
                        {
                            ErrorMessage = "Passwords do not match";
                            return false;
                        }
                    }
                }

                bool success = false;
                ErrorMessage = tracker.RegisterNewUser( NewUserName, one, out success);
                return success;
            }
            finally
            {
                if (ss_bstr1_ptr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(ss_bstr1_ptr);
                }
                if (ss_bstr2_ptr != IntPtr.Zero)
                {
                    Marshal.ZeroFreeBSTR(ss_bstr2_ptr);
                }
            }
        }


        #endregion //Methods
    }
}
